package linlist;
//Doppelt verkettete Lineare Liste mit Hilfe von Knoten
public class LinearList2{
  protected int anz;
  protected Knoten head;
  protected Knoten tail;

  public LinearList2(){
    head=new Knoten(null);
    tail=new Knoten(null);
    head.next=tail;
    tail.prev=head;
    anz=0;
  }

  protected Knoten getNode(int i){
    Knoten wander=head;
    while(wander.next!=tail && i-->=0)
      wander=wander.next;
    return wander;
  }

  public boolean isempty(){return anz==0;}

  public int length(){return anz;}

  public Object get(int wo){
    if(wo<0 || wo>=anz) return null;
    else return getNode(wo).data;
  }

  public void insert(Object obj, int wo){
    Knoten neu=new Knoten(obj);
    Knoten vor=getNode(wo-1);
    Knoten nach=vor.next;
    neu.next=nach;
    neu.prev=vor;
    vor.next=nach.prev=neu;
    anz++;
  }

  public Object delete(int wo){
    if(wo<0 || wo>=anz) return null;
    Knoten vor=getNode(wo-1);
    Knoten akt=vor.next;
    Knoten nach=akt.next;
    vor.next=nach;
    nach.prev=vor;
    anz--;
    return akt.data;
  }

  public int indexOf(Object obj, int start){
    if(start>=0 && start<anz){
      Knoten wander=getNode(start-1);
      while(wander.next!=tail){
        wander=wander.next;
        if(wander.data==obj) return start;
        start++;
      }
    }
    return -1;
  }

  public boolean equals(Object obj){
    if(!(obj instanceof LinearList2)) return false;
    LinearList2 ll=(LinearList2)obj;
    if(anz!=ll.anz) return false;
    Knoten a=head.next;
    Knoten b=ll.head.next;
    while(a!=tail){
      if(a.data!=b.data) return false;
      a=a.next;
      b=b.next;
    }
    return true;
  }

  public String toString(){
    Knoten wander=head.next;
    StringBuffer sb=new StringBuffer();
    while(wander!=tail){
      sb.append(wander.data.toString());
      sb.append(" ");
      wander=wander.next;
    }
    return sb.toString();
  }

  public static class Knoten{
    public Object data;
    public Knoten next;
    public Knoten prev;
    
    public Knoten(Object d){data=d;}
  }
}
